package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.FileUtil;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.config.BaiduConfig;
import com.heima.wemedia.config.CacheConfig;
import com.heima.wemedia.service.WmGreenScanService;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈辉
 * @data 2023 17:08
 * 基于百度云第三方接口实现
 */
@Service
public class WmBaiduScanServiceImpl implements WmGreenScanService {

    @Autowired
    private BaiduConfig baiduConfig;

    @Autowired
    private CacheConfig cacheConfig;

    /**
     * 百度云文本审核对接
     * @param text
     * @return
     */
    public Map<String, String> scanText(String text) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        Map<String, String> resultMap = new HashMap<>();
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = cacheConfig.get("token");
            if (StringUtils.isBlank(accessToken)) {
                accessToken = refreshToken();
            }
            String result = HttpUtil.post(url, accessToken, param);
            JSONObject json = JSONObject.parseObject(result);
            String conclusionType = json.getString("conclusionType");
            resultMap.put("conclusionType", conclusionType);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        return resultMap;
    }

    /**
     * 百度云图片审核对接
     * @param imgData 图片对应的字节数据
     * @return
     */
    public Map<String,String> scanImage(byte[] imgData) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        Map<String,String> resultMap = new HashMap<>();
        try {
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = cacheConfig.get("token");
            if (StringUtils.isBlank(accessToken)) {
                accessToken = refreshToken();
            }
            String result = HttpUtil.post(url, accessToken, param);
            JSONObject json = JSONObject.parseObject(result);
            resultMap.put("conclusionType", json.getString("conclusionType"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    //获取百度云token
    //@Scheduled(cron = "10 * * * * ?")
    //@PostConstruct
    private String refreshToken() {
        try {
            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + baiduConfig.getApiKey()
                            + "&client_secret=" + baiduConfig.getApiSecret() + "&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String token = response.body().string();
            token = JSONObject.parseObject(token).getString("access_token");
            cacheConfig.add("token", token);
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
